/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Logger from '../utils/Logger'
import Window from '@ohos.window'
import prompt from '@ohos.promptAction'
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import type { Permissions } from '@ohos.abilityAccessCtrl'
import { fileManager } from "../utils/fileUtils"
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@ohos.base';
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
import { wantAgent, WantAgent } from '@kit.AbilityKit';
import {WindowManager} from "../pages/WindowManager"
import { JSON } from '@kit.ArkTS'

let TAG = "_:_MainAbility "
const PERMISSIONS: Array<Permissions> =
  ['ohos.permission.MICROPHONE', 'ohos.permission.WRITE_MEDIA', 'ohos.permission.READ_MEDIA',
    'ohos.permission.KEEP_BACKGROUND_RUNNING',
    "ohos.permission.READ_IMAGEVIDEO",
    "ohos.permission.WRITE_IMAGEVIDEO",
    'ohos.permission.MEDIA_LOCATION',
  ]

export default class MainAbility extends UIAbility {
  backgroundRun() {
    let TAG = "_:_backgroundRun"
    console.log(TAG, "entered")
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          bundleName: "ohos.samples.harmonyagent",
          abilityName: "MainAbility"
        }
      ],
      actionType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };
    try {
      wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
        try {
          backgroundTaskManager.startBackgroundRunning(this.context,
            backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
            console.info(TAG, "Operation startBackgroundRunning succeeded");
          }).catch((error: BusinessError) => {
            console.error(TAG,
              `Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
          });
        } catch (error) {
          console.error(TAG,
            `Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
        }
      });
    } catch (error) {
      console.error(TAG,
        `Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
    }
  }

  onCreate(want, launchParam) {
    console.log("_:_D MainAbility onCreate")
  }

  onDestroy() {
    console.log("_:_D MainAbility onDestroy")
  }

  async startMainUi(context = this.context, param = {}) {
    console.log("_:_[want] attemping to startMainUi")
    let want: Want = {
      'deviceId': '',
      'bundleName': "ohos.samples.harmonyagent",
      'abilityName': "MainAbility",
      'parameters': param
    };
    context.startAbility(want).then(() => {
      console.log(`_:_[want] start second ability index page succeed with ${JSON.stringify(want)}`);
    }).catch((error: Error) => {
      console.error(`_:_[want]start second ability index page failedwith ${error}`);
    });
  }

  async onWindowStageCreate(windowStage) {
    // this.startMainUi()
    let TAG="_:_onWindowStageCreate"
    // console.log(TAG,"MainAbility onWindowStageCreate")
    console.log(TAG, 'Ability onWindowStageCreate',windowStage);
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    let authResults = await atManager.requestPermissionsFromUser(this.context, PERMISSIONS);
    if (authResults.authResults.includes(-1)) {
      return;
    }
    prompt.showToast({
      message: 'requestPermissionsFromUser success',
    });
    // console.log(TAG + "requestPermissionsFromUser success")
    // this.backgroundRun()

    WindowManager.windowStage=windowStage
    windowStage.setUIContent(this.context, "pages/index", null)
    windowStage.getMainWindow((err: BusinessError, data) => {
      try{
        // WindowManager.indexId = data.getWindowProperties().id.toString()
        console.log(TAG, "get  window properties", JSON.stringify(data.getWindowProperties()))
      }catch(e){
        console.error(TAG,"error getting indexid",JSON.stringify(e))
      }
      const errCode: number = err.code;
      if (errCode) {
        console.error(TAG,`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      this.hideSysBar(data)
    })
  }

  async immersive(windowClass) {
    try {
      let TAG = "_:_fullwindow"
      let promise = windowClass.setWindowLayoutFullScreen(true);
      promise.then(() => {
        console.info(TAG, 'Succeeded in setting the window layout to full-screen mode.');
      }).catch((err: BusinessError) => {
        console.error(TAG, 'Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
      });
    } catch (exception) {
      console.error(TAG, 'Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception));
    }
  }

  async hideSysBar(windowClass) {
    let names: Array<'status' | 'navigation'> = [];
    try {
      let promise = windowClass.setWindowSystemBarEnable(names);
      promise.then(() => {
        console.info(TAG, 'Succeeded in setting the system bar to be invisible.');
      }).catch((err: BusinessError) => {
        console.error(TAG,
          `Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(TAG,
        `Failed to set the system bar to be invisible. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }

  onWindowStageDestroy() {
    console.log("_:_D MainAbility onWindowStageDestroy")
  }

  onForeground() {
    console.log("_:_D MainAbility onForeground")
  }

  onBackground() {
    console.log("_:_D MainAbility onBackground")
  }
}
